﻿<%@ Page Language="VB" Debug="true" %>
<%@ Register TagPrefix="wmx" Namespace="Microsoft.Matrix.Framework.Web.UI" Assembly="Microsoft.Matrix.Framework, Version=0.6.0.0, Culture=neutral, PublicKeyToken=6f763c9966660626" %>
<%@ import Namespace="System.Data" %>
<%@ import Namespace="System.Data.OleDb" %>
<script runat="server">
    Sub Page_Load()
	Dim strsql as String
	strsql = ""

        Dim cnn As New OleDbConnection(ConfigurationSettings.AppSettings("strcnn"))
        Dim cmd as New OleDbCommand
        Dim pedidos as OleDbDataReader
        cnn.Open()
        cmd.Connection = cnn
    
	cmd.CommandText = "select id from pedido where pecas is Null or pecas = 0"
	pedidos = cmd.ExecuteReader()
	While pedidos.Read()
		dim totalpedido as OleDbDataReader
	        
	    Dim cnn2 As New OleDbConnection(ConfigurationSettings.AppSettings("strcnn"))
		Dim cmd2 as New OleDbCommand
	        
		cnn2.Open()
		cmd2.Connection = cnn2
		cmd2.CommandText = "select sum(quantidade) as total from produto where idpedido=" & pedidos("id")
		
		totalpedido = cmd2.ExecuteReader()
		totalpedido.Read()

		if IsDBNull(totalpedido("total")) then
			strsql = strsql & "delete * from pedido where id=" & pedidos("id") & ";"
		else
			if totalpedido("total") = 0 then
				strsql = strsql & "delete * from pedido where id=" & pedidos("id") & ";"
			else
				strsql = strsql & "update pedido set pecas=" & totalpedido("total") & " where id=" & pedidos("id") & ";"
			end if
		end if

		totalpedido.Close()
		cnn2.Close()
		
	End While

    pedidos.Close()
    
    dim vet
    vet = strsql.split(";")
    dim i as integer
	response.write(vet.length())
    for i=1 to vet.length()
		'response.write(vet(i) & "<br>")
		'cmd.CommandText = vet(i)
		'cmd.ExecuteNonQuery()
	next
	cnn.close()
    End Sub

</script>